package com.geleri.media{

import com.adobe.audio.format.WAVWriter;

import flash.display.Sprite;
import flash.events.IOErrorEvent;
import flash.events.NetStatusEvent;
import flash.events.SampleDataEvent;
import flash.events.SecurityErrorEvent;
import flash.media.Microphone;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.net.NetConnection;
import flash.net.Responder;
import flash.system.*;
import flash.utils.ByteArray;

import mx.collections.ArrayCollection;


public class Record extends Sprite{
	[Bindable]public var microphoneList:ArrayCollection;
	public var microphone:Microphone;
	
	[Bindable]public var isRecording:Boolean = false;
	
	[Bindable]public var isPlaying:Boolean = false;
	[Bindable]public var isSoundData:Boolean = false;
	
	[Bindable]public var soundData:ByteArray;
	public var sound:Sound;
	public var channel:SoundChannel;
	private var _gateway		: NetConnection;
	//public var tempDir:File = File.createTempDirectory()
	public function Record(){
		init();
		initGateway();
	}
	public function init():void
	{
		microphoneList = new ArrayCollection(Microphone.names);
		//cbMicChoices.selectedIndex=0;
	}
	public function initGateway():void
	{
		_gateway = new NetConnection();
		
		// Connect to gateway (Django needs trailing slash)
		_gateway.connect("http://127.0.0.1:8000/");
		
		// addEventListeners for IOErrors and gateway script errors
		_gateway.addEventListener(IOErrorEvent.IO_ERROR, onFault);
		_gateway.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onFault);
		_gateway.addEventListener(NetStatusEvent.NET_STATUS, onFault);
		
		// Set responder property to the object and methods that will receive the 
		// result or fault condition that the service returns.
		//var responder:Responder = new Responder( onSnapshotsResult, onFault );
		
		// Call remote service to fetch data
		//status_txt.text += "Loading snapshots...\n";
		//_gateway.call("getSnapshots", responder);
	}
	public function setAddr(addr:String):void{
		_gateway.connect(addr);
	}
	public function startRecording():void
	{
		isRecording = true;
		//microphone = Microphone.getMicrophone(cbMicChoices.selectedIndex);
		microphone = Microphone.getMicrophone(0);
		microphone.rate = 44;
		microphone.gain = 100;
		soundData = new ByteArray();
		trace("Recording");
		microphone.addEventListener(SampleDataEvent.SAMPLE_DATA, onSampleDataReceived);
		isSoundData=true;
	}
	
	public function stopRecording():void
	{
		isRecording = false;
		trace("Stopped recording");
		microphone.removeEventListener(SampleDataEvent.SAMPLE_DATA, onSampleDataReceived);
	}
	
	private function onSampleDataReceived(event:SampleDataEvent):void
	{
		while(event.data.bytesAvailable)
		{
			var sample:Number = event.data.readFloat();
			soundData.writeFloat(sample);
		}
	}
	
	public function soundCompleteHandler(event:Event):void
	{
		isPlaying = false;
	}
	
	public function startPlaying():void
	{
		isPlaying = true
		soundData.position = 0;
		sound = new Sound();
		sound.addEventListener(SampleDataEvent.SAMPLE_DATA, sound_sampleDataHandler);
		channel = sound.play();
		channel.addEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);    
	}
	
	public function sound_sampleDataHandler(event:SampleDataEvent):void
	{
		if (!soundData.bytesAvailable > 0)
		{
			return;
		}
		
		for (var i:int = 0; i < 8192; i++)
		{
			var sample:Number = 0;
			
			if (soundData.bytesAvailable > 0)
			{
				sample = soundData.readFloat();
			}
			event.data.writeFloat(sample); 
			event.data.writeFloat(sample);  
		}
		
	}
	
	public function stopPlaying():void
	{
		channel.stop();
		isPlaying = false;
	}
	public function save(term:String,pk:String,lang:String,model:String):void
	{
		//var outputStream:FileStream = new FileStream();
		var formatedSound:ByteArray = new ByteArray();
		var wavWriter:WAVWriter = new WAVWriter();
		//var newFile:File = event.target as File;
		
			soundData.position = 0;  // rewind to the beginning of the sample
			
			wavWriter.numOfChannels = 1; // set the inital properties of the Wave Writer
			wavWriter.sampleBitRate = 16;
			wavWriter.samplingRate = 44100;
			//outputStream.open(newFile, FileMode.WRITE);  //write out our file to disk.
			wavWriter.processSamples(formatedSound, soundData, 44100, 1); // convert our ByteArray to a WAV file.
			//outputStream.close();
			var responder:Responder = new Responder( onSaveResult, onFault );
			_gateway.call( "ByteArray.saveSound", responder, formatedSound,"wav",model,pk,lang,term );
		
	}
	private function onSaveResult( res:Object ): void	{
		trace(res);
	}
	
	private function onFault( error:* ): void	{
		// notify the user of the problem
		trace("Error Saving Audio!");
	}
	/*public function save():void
	{
		var docsDir:File = File.documentsDirectory;
		try
		{
			docsDir.browseForSave("Save As");
			docsDir.addEventListener(Event.SELECT, saveFile);
		}
		catch (error:Error)
		{
			trace("Save failed:", error.message);
		}
		
		
	}
	public function saveFile(event:Event):void
	{
		var outputStream:FileStream = new FileStream();
		var wavWriter:WAVWriter = new WAVWriter();
		var newFile:File = event.target as File;
		
		if (!newFile.exists)
		{
			soundData.position = 0;  // rewind to the beginning of the sample
			
			wavWriter.numOfChannels = 1; // set the inital properties of the Wave Writer
			wavWriter.sampleBitRate = 16;
			wavWriter.samplingRate = 44100;
			outputStream.open(newFile, FileMode.WRITE);  //write out our file to disk.
			wavWriter.processSamples(outputStream, soundData, 44100, 1); // convert our ByteArray to a WAV file.
			outputStream.close();
		}
	}
	*/
	
	public function toggleRecording():void
	{
		if (isRecording)
		{
			isRecording = false;
			//btnRecord.label = "Record";
			stopRecording();
		}
		else
		{
			isRecording = true;
			//btnRecord.label = "Stop Recording";
			startRecording();
		}
	}
	
	
	public function stop():void
	{
		if (isRecording)
		{
			stopRecording();
		}
		else if (isPlaying)
		{
			stopPlaying();
		}
	}
	public function clear():void
	{
		isSoundData=false;
		soundData = new ByteArray();
	}
	
}
}
